//
//  WeChooseViewController.m
//  代号：47
//
//  Created by 杨佩璋 on 15/6/30.
//  Copyright (c) 2015年 杨佩璋. All rights reserved.
//

#import "WeChooseViewController.h"
#import "WeChooseTableViewCell.h"
#import "RequestManager.h"
#import "WechooseModel.h"
#import "WeChooseDetailViewController.h"
#import "LORefresh.h"

#define kUrl @"http://api2.pianke.me/read/columns_detail"
#define kLimitNum 10

@interface WeChooseViewController ()<UITableViewDataSource,UITableViewDelegate,RequestDelegate>{
    
    NSInteger _limitNumber;
    
}

@property (nonatomic ,retain)NSMutableArray *chooseModel;//存放数组内容
@property (nonatomic ,retain)NSMutableArray *hotModelArr;//存放hot数组内容
@property (nonatomic ,retain)UITableView *mainTableView;//创建一个tableView
@property (nonatomic ,retain)UITableView *hotTableView;//创建一个hot tableView
@property (nonatomic ,retain)WeChooseDetailViewController *weDetailVC;//下一个界面的VC

@property (nonatomic ,copy)NSString *sortStr;//存放一个字符串，判断请求数据时候的sort类型（区分addtime和hot）

@end

@implementation WeChooseViewController


- (void)dealloc
{
    [_chooseModel release];
    [_hotModelArr release];
    [_mainTableView release];
    [_hotTableView release];
    [_sortStr release];
    [_weDetailVC release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _sortStr = @"addtime";
    _limitNumber = kLimitNum;
    [self requestData:_sortStr];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithTitle:@"hot" style:(UIBarButtonItemStylePlain) target:self action:@selector(handleBtnItemAction:)];
    self.navigationItem.rightBarButtonItem = btnItem;
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor orangeColor];
    [btnItem release];
    
    self.chooseModel = [NSMutableArray arrayWithCapacity:0];
    self.hotModelArr = [NSMutableArray arrayWithCapacity:0];
    
    [self createMainTableView];
    [self creatHotTableView];
    // Do any additional setup after loading the view.
    
    //刷新
    //mainTableView
    [_mainTableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [self requestData:@"addtime"];
    }];
    [_mainTableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _limitNumber += kLimitNum;
        [self requestData:@"addtime"];
    }];
    //hotTableView
    [_hotTableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [self requestData:@"hot"];
    }];
    [_hotTableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _limitNumber += kLimitNum;
        [self requestData:@"hot"];
    }];
    
    
    
}

- (void)handleBtnItemAction:(UIBarButtonItem *)item{

    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"hot"]) {
        self.navigationItem.rightBarButtonItem.title = @"new";
        _sortStr = @"hot";
        _limitNumber = kLimitNum;
        [self requestData:_sortStr];
        [UIView transitionFromView:_mainTableView toView:_hotTableView duration:1.5 options:UIViewAnimationOptionTransitionCurlDown completion:^(BOOL finished) {

        }];
    }else if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"new"]){
        self.navigationItem.rightBarButtonItem.title = @"hot";
        
        _sortStr = @"addtime";
        _limitNumber = kLimitNum;
        [UIView transitionFromView:_hotTableView toView:_mainTableView duration:1.5 options:UIViewAnimationOptionTransitionCurlUp completion:^(BOOL finished) {
            
        }];
    }
}


//hot界面tableView
- (void)creatHotTableView{
    _hotTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_width, kScreen_height - 64 - 49) style:UITableViewStylePlain];
    _hotTableView.delegate = self;
    _hotTableView.dataSource = self;
    [_hotTableView registerClass:[WeChooseTableViewCell class] forCellReuseIdentifier:@"wechooseCell"];
}

//主tableView
- (void)createMainTableView{
    
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_width, kScreen_height-64-49) style:UITableViewStylePlain];
    
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    [_mainTableView registerClass:[WeChooseTableViewCell class] forCellReuseIdentifier:@"wechooseCell"];
    [self.view addSubview:_mainTableView];
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([_sortStr isEqualToString:@"addtime"]){
        
        return _chooseModel.count;
        
    }else if([_sortStr isEqualToString:@"hot"]){
        
        return _hotModelArr.count;
        
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WeChooseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"wechooseCell"];
    
    if ([_sortStr isEqualToString:@"addtime"]){
        
        cell.chooseModel = _chooseModel[indexPath.row];
        
    }else if([_sortStr isEqualToString:@"hot"]){
     
        cell.chooseModel = _hotModelArr[indexPath.row];
        
    }

    
    
    return cell;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [WeChooseTableViewCell heightForCellForDifferentSize];
}


//点击cell进入下一个界面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    _weDetailVC = [[WeChooseDetailViewController alloc] init];
    
    if ([_sortStr isEqualToString:@"addtime"]){
        _weDetailVC.chooseModel = _chooseModel[indexPath.row];
    }else if([_sortStr isEqualToString:@"hot"]){
        _weDetailVC.chooseModel = _hotModelArr[indexPath.row];
    }
    [self.navigationController pushViewController:_weDetailVC animated:YES];
    

 
}



#pragma mark ------请求数据

- (void)requestData:(NSString *)sort{
//    NSLog(@" %d ... %s ... %ld",__LINE__,__FUNCTION__,_limitNumber);
    NSString *limitNumStr = [NSString stringWithFormat:@"%ld",(long)_limitNumber];
    RequestManager *request = [[RequestManager alloc] initWithRequestURL:kUrl requestModel:POST parameter:nil];
    request.parameterDic = [@{@"auth":@"0DcBnEH648f5DCMd9EMzqkTJxQ8qvYb6Oom1puDTw3cWP23txJShxd7f4",@"client":@"1",@"deviceid":@"0898EF65-3414-425C-B70A-D86B2D4ABAF0",@"limit":limitNumStr,@"sort":sort,@"start@":@"0",@"typeid":@"6",@"version":@"3.0.3"}mutableCopy] ;
    
    request.delegate = self;
    [request startRequest];
    
    
}
//请求完毕之后让代理对象执行的方法，同时把请求完整的data传给代理对象
- (void)requestDidFinishWithData:(NSData *)data{
    
    NSDictionary *mainDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    NSDictionary *dataDict = mainDict[@"data"];
    NSArray *listArr = dataDict[@"list"];
    
    
    
    
    if ([_sortStr isEqualToString:@"addtime"]) {
        [_chooseModel removeAllObjects];
        for (NSDictionary *tempDict in listArr) {
        WechooseModel *model = [[WechooseModel alloc] init];
        [model setValuesForKeysWithDictionary:tempDict];
        [_chooseModel addObject:model];
        [model release];
    }
        [_mainTableView reloadData];
//        NSLog(@" %d ... %s ... %@",__LINE__,__FUNCTION__,@"刷新了0");
        
    }else if([_sortStr isEqualToString:@"hot"]){
        [_hotModelArr removeAllObjects];
        for (NSDictionary *tempDict in listArr) {
            WechooseModel *model = [[WechooseModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDict];
            [_hotModelArr addObject:model];
            [model release];
        }
        [_hotTableView reloadData];
//        NSLog(@" %d ... %s ... %@",__LINE__,__FUNCTION__,@"刷新了1");
    }


    
    [_mainTableView.defaultHeader endRefreshing];
    [_mainTableView.defaultFooter endRefreshing];
    [_hotTableView.defaultHeader endRefreshing];
    [_hotTableView.defaultFooter endRefreshing];

}
//请求失败后把错误原因传值给代理对象
- (void)requestError:(NSError *)error{
    
    
}


@end
